Can this algorithm be made more efficient